package com.yksj.healthtalk.ui.doctorstation;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.DoctorSettingHisotryAdapter;
import com.yksj.healthtalk.adapter.DoctorSettingHisotryAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DoctorPatient;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.recharge.ChoiseDateActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.TimeUtil;
/**
 * 咨询客户历史
 * @author Administrator
 *
 */
public class DoctorSettingClientHistoryActivity extends BaseFragmentActivity implements OnClickListener, OnRefreshListener2<ListView>, OnItemClickListener, onClickFriendHeadListener, OnCheckedChangeListener{
	private TextView nowTime;//日历当前显示时间
	private PullToRefreshListView refreshListView;
	private ListView mListView;
	private List<DoctorPatient> mlList=new ArrayList<DoctorPatient>();
	private DoctorSettingHisotryAdapter adapter;
	private int num=1;
	private PopupWindow mPopBottom;
	private String date = "0";
	private String serviceTypeId = "0";//分类
	private int number=0;//请求了多少个数据
	List<RightEntityTag> entityTags=new ArrayList<RightEntityTag>();
	
	BroadcastReceiver receiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
					}}
		}
	};
	
	private View mPopBottomView;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_client);
		initView();
		initData();
	}
	@Override
	protected void onResume() {
		super.onResume();
		initData();
	}
	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}
	
	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}
	
	private void initData() {
		HttpRestClient.doHttpDoctorOption(SmartFoxClient.getLoginUserId(),"3","20", String.valueOf(num), date,serviceTypeId, "0", 
				new ObjectHttpResponseHandler(this) {
					@Override
					public Object onParseResponse(String content) {
						try {
							final JSONObject object=new JSONObject(content);
							if(object.has("error_message")){
								return null;
							}
							if(entityTags.size()==0){
								JSONArray array = object.optJSONArray("serviceType");
								entityTags.add(new RightEntityTag("0","全部"));
								for (int i = 0; i < array.length(); i++) {
									JSONObject obj = (JSONObject) array.get(i);
									RightEntityTag tag=new RightEntityTag(obj.optString("SERVICE_TYPE_ID"),obj.optString("SERVICE_TYPE"));
									entityTags.add(tag);
								}
							}
							return DoctorPatient.parseToList(object.getString("dataList").toString());
						} catch (Exception e) {
							return null;
						}
					}
					@Override
					public void onSuccess(Object response) {
						titleRightBtn2.setVisibility(View.VISIBLE);
						if(response!=null){
							List<DoctorPatient> list=(List<DoctorPatient>)response;
							if(num==1)number=list.size();
							adapter.updateData(list);
							adapter.notifyDataSetChanged();
						}
						super.onSuccess(response);
					};
					
					public void onFinish() {
						super.onFinish();
						refreshListView.onRefreshComplete();
					};
				}
		);
	}

	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("历史客户");
		titleRightBtn2.setText("服务类型");
		titleRightBtn2.setOnClickListener(this);
		
		nowTime = (TextView)findViewById(R.id.now_time);
		nowTime.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
		nowTime.setOnClickListener(this);
		findViewById(R.id.calender).setOnClickListener(this);
		
		refreshListView = (PullToRefreshListView) findViewById(R.id.listview_fragment);
		mListView = refreshListView.getRefreshableView();
		adapter=new DoctorSettingHisotryAdapter(this,mlList);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		adapter.setonClickFriendHeadListener(this);
		refreshListView.setOnRefreshListener(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode!=RESULT_OK)return;
		switch (requestCode) {
		case 1000:
			if(data!=null){
				Bundle extras = data.getExtras();
				if(extras.containsKey("all")){
					date="0";
					adapter.entities.clear();
				}else{
					if(extras.containsKey("nothing"))return;
					String string = extras.getString("date");
					String string1 = extras.getString("year");
					nowTime.setText(string1+"-"+string);
					date=string1+string;
					
				}
				adapter.entities.clear();
				num=1;
			}else{
					date="0";
					num=1;
					nowTime.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
				}
			initData();
			break;
		}
	}
	
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			setResult(RESULT_OK, getIntent());
			finish();
			break;
		case R.id.title_right2:
			if(entityTags.size()>0)
			showMenu(v);
			break;
		case R.id.calender:
		case R.id.now_time:
			Intent intent=new Intent(this,ChoiseDateActivity.class);
			if(nowTime.getText().toString().length()<5){
				intent.putExtra("date", TimeUtil.getMoneyTime());
			}else{
				intent.putExtra("date", nowTime.getText().toString());
			}
			startActivityForResult(intent,1000);
			break;
		}
	}
	
	private void showMenu(View view) {
		if (mPopBottom == null) {
			LayoutInflater inflater = LayoutInflater.from(this);
			mPopBottomView = inflater.inflate(R.layout.doctor_client_history, null);
			mPopBottomView.setBackgroundResource(R.drawable.popmenu_white_bg);
			mPopBottom = new PopupWindow(mPopBottomView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);
			mPopBottom.setBackgroundDrawable(new BitmapDrawable());
			mPopBottom.setFocusable(true);
			RadioGroup radioGroup = (RadioGroup) mPopBottomView.findViewById(R.id.radiogroup);
			for (int i = 0; i < entityTags.size(); i++) {
				RadioButton mButton= (RadioButton) radioGroup.getChildAt(i);
				mButton.setVisibility(View.VISIBLE);
				mButton.setText(entityTags.get(i).getName());
			}
			radioGroup.setOnCheckedChangeListener(this);
		} else if (mPopBottom.isShowing()) {
			mPopBottom.dismiss();
			return;
		}
		mPopBottom.showAsDropDown(view);
	}


	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		if(number>=20)
			num++;
		initData();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		if(number>=20)
			num++;
		initData();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			CustomerInfoEntity entity =new CustomerInfoEntity();
			entity.setId(mlList.get(position-1).getCustomerId());
			entity.setName(mlList.get(position-1).getCustomerNickname());
			if (entity.isShowDoctorV()) {
				Intent intent = new Intent(this,DoctorMainActivity.class);
				intent.putExtra("id", entity.getId());
				intent.putExtra("type", "1");
				intent.putExtra("positon", position-1);
				startActivityForResult(intent, 0);
			} else {
				FriendHttpUtil.onItemClick(this, entity);
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void onClickFriendHead(DoctorPatient object, int positon) {
		DoctorPatient mPatient=(DoctorPatient) object;
		PersonInfoUtil.choiceActivity(mPatient.getCustomerId(), this, mPatient.getRoleId());
	}
	
	
	class RightEntityTag{
		String id;
		String name;
		public RightEntityTag(String id, String name) {
			super();
			this.id = id;
			this.name = name;
		}
		
		public RightEntityTag() {
			super();
		}

		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		RadioButton view = (RadioButton)mPopBottomView.findViewById(checkedId);
		if(!view.isChecked())return ;
		for (int i = 0; i < entityTags.size(); i++) {
			if(view.getText().toString().equals(entityTags.get(i).getName())){
				num=1;
				adapter.entities.clear();
				serviceTypeId=entityTags.get(i).getId();
				titleRightBtn2.setText(entityTags.get(i).getName());
				mPopBottom.dismiss();
				initData();
			}
		}
	}


}
